import requests
import json
import time
from bs4 import BeautifulSoup


class FishPiBot:
    def __init__(self):
        self.cookie = ''
        #实现最简单的部分
    def get_api_content(self):
        """从API获取内容"""
        try:
            url = "https://api.yviii.com/yiyan/yi.php"
            response = requests.get(url, timeout=10)
            response.encoding = 'utf-8'
            html = response.text.strip()

            soup = BeautifulSoup(html, 'html.parser')
            text_content = soup.get_text().strip()

            if text_content:
                return text_content
            else:
                return html

        except Exception as e:
            print(f"✗ 获取API内容失败: {e}")
            return None

    def send_message(self, message):
        """发送单条消息到FishPi聊天室"""
        session = requests.Session()
        session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Content-Type': 'application/json; charset=UTF-8',
            'Referer': 'https://fishpi.cn/cr',
            'Origin': 'https://fishpi.cn',
            'Cookie': self.cookie
        })

        url = "https://fishpi.cn/chat-room/send"
        json_data = {
            "content": message,
            "client": "Web/PC网页端"
        }

        try:
            response = session.post(url, json=json_data, timeout=10)
            if response.status_code == 200:
                result = response.json()
                if result.get('code') == 0:
                    print(f"✓ 消息发送成功: {message}")
                    return True
                else:
                    print(f"✗ 发送失败: {result.get('msg', '未知错误')}")
                    return False
            else:
                print(f"✗ 请求失败，状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"✗ 发送异常: {e}")
            return False

    def run(self, count=10):
        # 运行程序
        sent_count = 0

        print(f"开始运行消息发送程序，计划发送 {count} 次，每分钟一次...")
        print("按 Ctrl+C 停止程序")

        while sent_count < count:
            try:
                print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] 开始执行第 {sent_count + 1}/{count} 次任务...")

                # 从API获取内容并发送
                api_content = self.get_api_content()
                api_content2 = "点歌 雨后的黄昏是悲伤的"
                if api_content:
                    success = self.send_message(api_content2)
                    if success:
                        sent_count += 1
                        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 任务完成 ({sent_count}/{count})")
                    else:
                        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 任务失败")
                else:
                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 获取内容失败，跳过本次发送")

                # 如果还未达到次数，等待60秒
                if sent_count < count:
                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 等待下一分钟...")
                    time.sleep(60*30) #主要修改的地方 此时已经是半个小时

            except KeyboardInterrupt:
                print(f"\n程序已手动停止，共发送 {sent_count} 条消息")
                break
            except Exception as e:
                print(f"程序执行异常: {e}")
                if sent_count < count:
                    time.sleep(60*30)  # 发生异常也等待60秒再继续 此处可以不改

        print(f"\n 程序执行完成！共发送 {sent_count} 条消息")


def main():
    """主函数"""
    # 获取用户输入的执行次数
    try:
        count = int(input("请输入要执行的次数（每分钟一次）: "))
        if count <= 0:
            print("次数必须大于0")
            return
    except ValueError:
        print("请输入有效的数字")
        return

    # 创建机器人实例并运行
    bot = FishPiBot()
    bot.run(count)


if __name__ == "__main__":
    main()
